<template>
  <div :class="{'disabled': disabled}">
    <!-- :class="{ disabled: uploadDisabled, 'no-del': !readOnly }" -->
    <el-upload
      action="//upload.qiniup.com/"
      list-type="picture-card"
      accept=".bmp, .gif, .jpg, .jpeg, .png, .pdf, image/bmp, image/gif, image/jpg, image/jpeg, image/png, image/pdf"
      :data="qiniuData"
      :limit="limit"
      :file-list="fileList"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :on-success="handleSuccess"
      :before-upload="beforeAvatarUpload"
      :before-remove="beforeRemove"
      :on-exceed="handleExceed"
      :disabled="disabled"
      :multiple="limit > 1"
    >

      <div slot="trigger" class="add-empty">
        <!-- 在这里添加自定义内容 -->
        <i class="el-icon-plus" />
        <div v-show="!qrcodeShow" class="mask" :style="dynamicStyles">
          <div class="upload-item" style="pointer-events: all;" :style="{ 'cursor': disabled ? 'not-allowed' : 'pointer' }">
            <img :src="require('@/assets/web-upload.png')" alt="本地上传">
            <div>本地上传</div>
          </div>
          <div class="upload-item phone-upload" style="pointer-events: all;" :style="{ 'cursor': disabled ? 'not-allowed' : 'pointer' }" @click.stop="phoneUpload">
            <img :src="require('@/assets/phone-upload.png')" alt="手机上传">
            <div>手机上传</div>
          </div>
        </div>
        <div v-show="qrcodeShow" :style="dynamicStyles" class="qrcode-wrapper">
          <div ref="qrcodeRef" class="qrcode-content" />
          <i class="el-icon-close" @click.stop="qrcodeClose" />
        </div>
      </div>
      <div v-if="itemAttrs.label !== '电子签名'" slot="tip" class="el-upload__tip">{{ placeholder }} {{ sizeTip }}</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import { queryQiniuyunUploadToken, queryUuid, selectUploadurlList } from '@/api'
  import { mapGetters } from 'vuex'
  import QRCode from 'qrcodejs2'
  //   import componentMinxins from '@/views/designer/common/form/ComponentMinxins'

  export default {
    name: 'AddFileList',
    // mixins: [componentMinxins],
    props: {
      readOnly: {
        type: Boolean,
        default: true
      },

      /*
      item-attrs:{
       __config__:{
        maxNumber，
        uploadType，
        title
       }
      }
      uploadType:
        非必要值
        0 商品
        1 正面
        2 反面
        3 营业执照
        */

      itemAttrs: {
        type: Object,
        default: () => ({ prop: 'SysUserPage_imageUrl', viewParameter: { }})
      },
      defaultValue: {
        type: [String, Array, Object]
      }
    },
    data() {
      return {
        tokenInfo: {},
        qiniuData: { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: '',
          bucket: ''
        },
        fileList: [],
        addFileList: [], // 用于存储所有的图片，包括原来已有的
        dialogImageUrl: '',
        domainName: '',
        dialogVisible: false,
        qrcodeShow: false,
        timer: null,
        dataNumber: null
      }
    },
    computed: {
      limit() {
        return this.itemAttrs && this.itemAttrs.__config__ && this.itemAttrs.__config__.maxNumber ? this.itemAttrs.__config__.maxNumber : 5
      },
      disabled() {
        return !this.itemAttrs.canEdit
      },
      mergeFileList() {
        return this.addFileList.map(item => ({ url: item.url, httpUrl: item.httpUrl }))
      },
      uploadDisabled() {
        // const map = new Map()
        // const length = this.mergeFileList.concat(this.fileList.map(item => ({ url: item.url }))).filter(item => !map.has(item.url) && map.set(item.url, 'has')).length
        const length = this.fileList.length
        return length >= this.itemAttrs && this.itemAttrs.__config__ && this.itemAttrs.__config__.maxNumber ? (this.itemAttrs.__config__.maxNumber ? this.itemAttrs.__config__.maxNumber : 1) : 1
      },
      dynamicStyles() {
        console.log('this.fileList', this.fileList)
        console.log('this.addFileList', this.addFileList)
        return {
          left: `${155 * this.addFileList.length}px`
        }
      },
      placeholder() {
        return this.itemAttrs && this.itemAttrs.__config__ && this.itemAttrs.__config__.placeholder ? this.itemAttrs.__config__.placeholder : ''
      },
      maxSize() {
        return this.itemAttrs && this.itemAttrs.__config__ && this.itemAttrs.__config__.placeholder ? (this.itemAttrs.__config__.maxSize || 10) : 10
      },
      sizeTip() {
        return this.maxSize > 0 ? `| 每张图不超过${this.maxSize}MB` : ''
      },
      ...mapGetters([
        'userInfo'
      ])
    },
    watch: {
      mergeFileList: {
        handler(val) {
          console.log('val', val)
          this.$emit('changeFormItem', { ...this.qiniuData, url: val.map(item => item.httpUrl).join(','), ...this.itemAttrs.__config__ })
        },
        deep: true,
        immediate: true
      },
      defaultValue: {
        handler(val) {
          if (!val) {
            this.fileList = []
            this.addFileList = []
            return
          }
          // 如果val不是字符串类型或数组,return
          if (typeof val !== 'string' || typeof val.length !== 'number') return
          if (val.startsWith('data:')) {
            this.fileList = [{ url: val }]
            this.addFileList = [{ url: val }]
          } else {
            this.fileList = val.split(',').map(item => {
              return {
                url: 'http://image.haoyunqi.com.cn/' + item,
                httpUrl: item
              }
            })
            this.addFileList = val.split(',').map(item => {
              return {
                url: 'http://image.haoyunqi.com.cn/' + item,
                httpUrl: item
              }
            })
          }
        },
        immediate: true,
        deep: true
      }
    },
    beforeDestroy() {
      clearInterval(this.timer)
    },
    created() {
      this.getQiniuyunUploadToken()
    },
    methods: {
      beforeAvatarUpload(file) {
        this.qiniuData.key = this.userInfo.userId + '_' + new Date().getTime() + '_' + file.name
        const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase()
        const whiteList = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pdf']
        if (whiteList.indexOf(fileSuffix) === -1) {
          this.$message.error('上传的文件类型不正确')
          return Promise.reject(false)
        }
        const isLt = file.size / 1024 / 1024 <= this.maxSize
        if (!isLt) {
          this.$message.error('上传文件大小不能超过' + this.maxSize + 'MB')
          return Promise.reject(false)
        }
      },
      beforeRemove() {
        if (!this.readOnly) return false
        // 弹出二次确认框,确认后才执行删除操作，否则不执行
        // return this.$confirm(this.$t('_Common.ConfirmDelete'), this.$t('_Common.Prompt'), {
        //   confirmButtonText: this.$t('_Common.Confirm'),
        //   cancelButtonText: this.$t('_Common.Cancellation'),
        //   type: 'warning'
        // }).then(() => {
        //   return true
        // }).catch(() => {
        //   return Promise.reject(false)
        // })
      },
      handleExceed(files, fileList) {
        this.$message.warning(`限制${this.limit} 个文件，本次选择了 ${files.length}个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken({ fileUsageType: this.itemAttrs.prop.split('_')[1] })
        this.qiniuData.token = res.data
      },
      handleRemove(file, fileList) {
        // if (file.response) file.url = file.response.key
        // 如果文件类型是符合要求的文件类型
        if (file.name) {
          const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1) // 获取文件后缀名
          const isType = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'pdf'].includes(fileSuffix) // 检查文件后缀名是否在格式接受列表中
          if (!isType) return
        }
        // 如果当前文件是在文件列表中的才继续往下执行，否则返回
        if (!this.fileList.map(item => item.url).includes(file.url)) return
        this.mergeFileList.splice(this.mergeFileList.map(item => item.url).indexOf(file.url), 1) // 从合并文件列表中移除当前文件
        this.fileList.splice(this.fileList.map(item => item.url).indexOf(file.url), 1) // 从文件列表中移除当前文件
        this.addFileList.splice(this.addFileList.map(item => item.url).indexOf(file.url), 1)
        this.$emit('changeFormItem', this.fileList.map(item => item.url).join(',')) // 触发changeFormItem事件，将文件列表中的url拼接成字符串并传递给父组件
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleChange(file, fileList) {
        this.qiniuData.key = this.userInfo.userId + '_' + new Date().getTime() + file.name
      },
      handleSuccess(res, file, fileList) {
        console.log('1fileList', fileList)
        console.log('1file', file)
        // this.addFileList = fileList.filter(item => item.status === 'success').map(item => {
        //   return {
        //     url: item.response ? '//' + this.domainName + '/' + item.response.key : item.url
        //   }
        // })
        // 如果选择的多个文件，那么fileList是一个数组，否则是一个对象
        if (fileList.length) {
          if (fileList.every((it) => it.status === 'success')) {
            // 等待所有文件都上传完成，这里注意fileList是所有的文件（包含已上传的）
            fileList.map((item) => {
              item.response &&
                this.addFileList.push({
                  name: item.name,
                  url: item.response ? 'http://image.haoyunqi.com.cn/' + item.response.key : item.url,
                  httpUrl: item.response ? item.response.key : item.url
                }) // 只push新上传的 （带有response）
            })
          }
        } else {
          this.addFileList.push({
            name: file.name,
            url: file.response ? 'http://image.haoyunqi.com.cn/' + file.response.key : file.url,
            httpUrl: file.response ? file.response.key : file.url
          })
        }
        fileList.forEach(item => {
          item.httpUrl = item.response.key
          item.url = 'http://image.haoyunqi.com.cn/' + item.response.key
        })
        this.fileList = fileList
        console.log('this.addFileList', this.addFileList)
        console.log('this.fileList', this.fileList)
      },
      // 点击手机上传
      phoneUpload() {
        // 如果是禁用状态,return
        if (this.disabled) return
        this.qrcodeShow = true
        this.creatQrCode()// 必须公网地址
      },
      startTime(dataNumber) {
        if (this.timer) {
          clearInterval(this.timer)
        }
        this.timer = setInterval(() => {
          setTimeout(() => {
            this.queryUploadImg(dataNumber)
          }, 4000)
        }, 2000)
      },
      queryUploadImg(dataNumber) {
        if (this.dataNumber === dataNumber) {
          this.qrcodeClose()
          return
        }
        console.log('dataNumber', dataNumber)
        selectUploadurlList({ uuid: dataNumber }).then(res => {
          if (res.data) {
            this.dataNumber = dataNumber
            const responseList = res.data.url.split(',')
            responseList.forEach(item => {
              const obj = {
                url: 'http://image.haoyunqi.com.cn/' + item,
                httpUrl: item,
                status: 'success'
              }
              this.fileList.push(obj)
              // 如果图片url相同，则不必再次添加
              if (this.addFileList.map(item => item.url).indexOf(obj.url) === -1) {
                this.addFileList.push(obj)
              }
            })
            this.qrcodeClose()
          }
        })
      },
      clearTimer() {
        clearInterval(this.timer)
      },
      // 生成二维码
      async creatQrCode() {
        const { data } = await queryUuid()
        const maxCount = this.itemAttrs && this.itemAttrs.__config__ && this.itemAttrs.__config__.maxNumber ? this.itemAttrs.__config__.maxNumber - this.fileList.length : 5
        const domainUrl = window.location.origin
        const capture = this.itemAttrs.__config__.capture ? 1 : 0 // 是否仅允许拍照上传
        const url = `${domainUrl}/#/components/phoneUpload?maxCount=${maxCount}&title=${this.itemAttrs.__config__.title}&uuid=${data}&capture=${capture}`
        console.log('url', url)
        // 检查 qrcodeObj 是否存在并且清除它
        this.$refs.qrcodeRef.innerHTML = ''

        this.qrcodeObj = new QRCode(this.$refs.qrcodeRef, {
          text: url,
          width: 118,
          height: 118,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.M
        })
        this.startTime(data)
      },
      // 关闭二维码
      qrcodeClose() {
        this.qrcodeObj.clear()
        this.clearTimer()
        this.qrcodeShow = false
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/ .el-upload-list__item-status-label {
  display: none !important;
}
.disabled {
  cursor: not-allowed;
}
/deep/ .el-upload-list__item {
  transition: none;
}
.mask {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 148px;
  height: 148px;
  color: #fff;
  pointer-events: none;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 4px;
  visibility: hidden;
  .upload-item {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-direction: column;
    img {
      position: absolute;
      top: 25%;
      width: 20px;
    }
  }
}
.add-empty {
  &:hover .mask {
    visibility: visible;
  }
}
// .el-upload{
//   &:hover .mask {
//     visibility: visible;
//   }
// }
.qrcode-wrapper {
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 148px;
  height: 148px;
  padding: 29px;
  pointer-events: all;
  background: #fff;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.16);
  .qrcode-content {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 119px;
    height: 119px;
  }
  .el-icon-close {
    position: absolute;
    top: 0;
    right: 0;
    font-size: 16px;
    cursor: pointer;
  }
}
.no-del {
  /deep/ .el-upload-list__item-delete {
    display: none !important;
  }
}
</style>
